import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { ENUM } from 'utils/constants.js';
import * as actions from '../actions/index';
import { access } from 'components/accessContainer/util';
import Root2 from './content';
import MessagePage from 'components/messagePage';
import ImportingPage from './importing';
import { Loading, Message } from '@teamix/ui';
import ImportFailPage from './importFail';
import {
  getProjectInfo,
  resetIsProjectInfoFetched,
  setImportStatus,
} from 'pages/index/pages/project/actions';
import { updatePageInfo } from 'pages/index/actions';
import { enterPage } from 'utils/track';
import Lead from 'components/Lead/index';
import utils from 'utils';
import intl from '../../../../../../../locale';
// import Watermark from 'components/watermark';

const PROJECT_VIEW_FILE = [
  'REPORTER',
  'ORG_MEMBER',
  'DEVELOPER',
  'MASTER',
  'OWNER',
  'ORG_ADMIN',
  'ORG_OWNER',
  'ADMIN',
];

const IMPORT_STATUS_ENUM = {
  started: 'started', // 导入中
  none: 'none', // 正常页面
  finished: 'finished', // 导入刚完成
  failed: 'failed', // 导入失败
  stopping: 'stopping',
};

class RootImage extends Component {
  // 导入状态从started/stopping开启
  importTimer = null;

  componentDidMount() {
    // 判断是否开启定时器
    this.openTimer();
    this.handleProjectExist();

    this.props.getHttpsAccount();
    setTimeout(() => {
      this.renderLeadComponent();
    }, 10000);
    enterPage('Repo-Files', {
      sendPerf: false,
    });
    document.body.classList.add('no-min-width');
  }

  componentDidUpdate(prevProps) {
    const isPrevStartedOrStopping = ['started', 'stopping'].includes(
      prevProps.projectInfo.import_status,
    );
    const isStartedOrStopping = ['started', 'stopping'].includes(
      this.props.projectInfo.import_status,
    );

    if (
      prevProps.projectInfo.import_status === 'stopping' &&
      this.props.projectInfo.import_status !== 'stopping'
    ) {
      this.props.updateData({
        isStoppingImport: false,
      });
    }

    if (isPrevStartedOrStopping && !isStartedOrStopping) {
      clearInterval(this.importTimer);
      if (this.props.projectInfo.import_status === 'finished') {
        Message.success({
          title: intl.get({
            id: 'code-assets.projectFiles.containers.root.ImportCompleted',
            defaultMessage: '导入完成',
          }),
        });
        window.location.reload();
      }
      this.handleProjectExist();
    }
    if (!isPrevStartedOrStopping && isStartedOrStopping) {
      this.openTimer();
    }
  }

  handleProjectExist = () => {
    const { isEmpty, isExist } = this.getProjectInfoFromPageInfo();
    // 获取库的基本信息和统计信息
    if (isExist && this.getViewAuth()) {
      // 获取组件的信息
      !isEmpty && this.initLeftTree();
      // 空仓库需要将左侧树置为true,显示内容
      isEmpty &&
        this.props.updateData({
          isInitedLeftTree: true,
        });

      !isEmpty && this.props.getIpWhiteList();
      // 获取下载按钮的权限等等
      this.props.getCloneDownloadSetting();
    }
  };

  componentWillUnmount() {
    this.importTimer && clearInterval(this.importTimer);
    this.getAllFilesTimeout && clearTimeout(this.getAllFilesTimeout);
    this.props.resetData();
    document.body.classList.remove('no-min-width');
  }

  openTimer = () => {
    // 是导入中或者终止中
    const isStartedOrStopping = ['started', 'stopping'].includes(
      this.props.projectInfo.import_status,
    );
    // 开启定时器
    if (isStartedOrStopping) {
      clearInterval(this.importTimer);

      this.importTimer = setInterval(() => {
        this.props.getParentProjectInfo();
      }, 3000);
    } else {
      clearInterval(this.importTimer);
    }
  };

  getProjectInfoFromPageInfo = () => {
    const { pathResource } = this.props.pageInfo || {};
    const isExist = pathResource.isExist === 'true';
    const isEmpty = pathResource.isEmpty === 'true';
    return {
      isEmpty,
      isExist,
      role: pathResource.role,
    };
  };

  initLeftTree = () => {
    const { filesViewType, resourceType, getInitTreeData, getRightTreeData, resourcePath } =
      this.props;
    const resourcePathArr = resourcePath.split('/');
    const fileName = resourcePathArr[resourcePathArr.length - 1];
    // 获取树
    if (filesViewType === 'tree') {
      const path =
        resourceType === 'blob' ? resourcePath.replace(`/${fileName}`, '') : resourcePath;
      // 获取右侧数据的内容接口提前,首页readme依赖左侧树，继续放后面请求
      if (path) {
        getRightTreeData(resourcePath);
      }
      getInitTreeData(path, () => {
        !path && getRightTreeData(resourcePath);
      });
    }

    // 在空闲时获取所有的树文件
    this.getAllFilesTimeout = setTimeout(() => {
      const { repoSize } = this.props;
      if (repoSize && Number(repoSize) < 200) {
        this.props.getAllFiles();
      }
    }, 3000);
  };

  getViewAuth = () => {
    const { projectInfo } = this.props;

    // Reporter 和 Guest 身份，没有写入文件权限
    // Guest 身份，没有浏览文件权限
    const { role } = this.getProjectInfoFromPageInfo();
    // TODO： 编辑权限在下拉框中需要判定
    // const isWriteFileRole =
    //   role === 'Developer' || role === 'Master' || role === 'Owner' || role === 'ADMIN';
    // const hasWriteFileAuth = isWriteFileRole;

    const isViewFileRole = access(PROJECT_VIEW_FILE, role);

    // TODO 用户身份结合仓库私有还是公开，决定最终权限  还有一些tab的隐藏没有处理
    let isPrivate = true;
    if (
      ENUM.visibility_level_text[projectInfo.visibility_level] &&
      ENUM.visibility_level_text[projectInfo.visibility_level] !== 'private'
    ) {
      isPrivate = false;
    }

    const hasViewFileAuth = isViewFileRole || !isPrivate;
    return hasViewFileAuth;
  };

  renderProjectFileJsx = () => {
    const {
      projectInfo,
      stopImportProject,
      isStoppingImport,
      getParentProjectInfo,
      isInittingImport,
      isRemovingProject,
    } = this.props;

    const { isExist } = this.getProjectInfoFromPageInfo();
    //  状态为started, stopping，导入中; 其他状态，根据isExist: false 显示失败页面，true显示正常页面
    //  特例：导入完成时isExist还是不存在，页面应该保留在导入中的状态，等待window.reload
    if (
      [IMPORT_STATUS_ENUM.started, IMPORT_STATUS_ENUM.stopping].includes(
        projectInfo.import_status,
      ) ||
      (!isExist && projectInfo.import_status === 'finished')
    ) {
      return (
        <ImportingPage
          projectInfo={projectInfo}
          stopImportProject={stopImportProject}
          isStoppingImport={isStoppingImport}
        />
      );
    }

    if (!isExist) {
      return (
        <ImportFailPage
          removeProject={this.props.removeProject}
          initEmptyProject={this.props.initEmptyProject}
          projectInfo={projectInfo}
          getProjectInfo={getParentProjectInfo}
          isRemovingProject={isRemovingProject}
          isInittingImport={isInittingImport}
          setImportStatus={setImportStatus}
        />
      );
    }

    // FIXME: 此处需处理 isTooLarge 和 isNavHidden
    // const isTooLarge = utils.isTooLarge(this.props.pageInfo.pathResource);
    // const marginStyle = isTooLarge ? { marginTop: '35px' } : {};
    return (
      <>
        {/* <div
          style={isEmpty ? { ...marginStyle } : { left: '300px', width: 'calc(100% - 300px)', ...marginStyle }}
          className={
            isEmpty ? 'project-content' : `layout-bottom ${this.props.isNavHidden ? 'no-nav' : ''}`
          }
        > */}
        <Root2 />
        {/* </div> */}
      </>
    );
  };

  renderLeadComponent = () => {
    const { organization_id } = window.FORCE.organization;
    // 1024 活动企业不展示新手任务
    if (organization_id !== '5f7051259cffa29cfdd39e47') {
      return;
    }

    const hasCloseGuide = utils.getCache('guide_1024', false);
    if (hasCloseGuide) {
      return;
    }

    const idName = 'mountLeadEl';
    let mountLeadEl = document.getElementById(idName);
    if (!mountLeadEl) {
      mountLeadEl = document.createElement('div');
      mountLeadEl.id = idName;
      document.body.appendChild(mountLeadEl);
    }
    // 新手引导逻辑块
    ReactDOM.render(
      <Lead
        onClose={() => {
          utils.setCache('guide_1024', true, false);
          ReactDOM.unmountComponentAtNode(document.getElementById(idName));
        }}
      />,

      document.getElementById(idName),
    );
  };

  render() {
    const {
      isProjectInfoFetched,
      // genWatermarkimage,
    } = this.props;

    const hasViewFileAuth = this.getViewAuth();
    if (!isProjectInfoFetched) {
      return (
        <div className="loading-project-info">
          <Loading />
        </div>
      );
    }

    return (
      <React.Fragment>
        {/* <Watermark genWatermarkimage={genWatermarkimage}> */}
        {hasViewFileAuth ? (
          this.renderProjectFileJsx()
        ) : (
          <MessagePage
            pictureUrl="https://img.alicdn.com/tfs/TB14JNzD1uSBuNjy1XcXXcYjFXa-700-700.png"
            title={intl.get({
              id: 'code-assets.projectFiles.containers.root.NoAccessPermission',
              defaultMessage: '无访问权限',
            })}
            desc={intl.get({
              id: 'code-assets.projectFiles.containers.root.ContactTheDatabaseAdministratorTo',
              defaultMessage: '请联系库管理员进行添加',
            })}
          />
        )}
        {/* </Watermark> */}
      </React.Fragment>
    );
  }
}

export default connect(
  (state) => {
    return {
      ...state.project.projectFiles,
      projectInfo: state.project.root.projectInfo,
      isProjectInfoFetched: state.project.root.isProjectInfoFetched,
      pageInfo: state.root.pageInfo,
      genWatermarkimage: state.project.root.genWatermarkimage,
    };
  },
  (dispatch) =>
    bindActionCreators(
      {
        ...actions,
        getParentProjectInfo: getProjectInfo,
        updatePageInfo,
        resetIsProjectInfoFetched,
        setImportStatus,
      },
      dispatch,
    ),
)(RootImage);
